package servlet.request;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Enumeration;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Create By IntelliJ IDEA
 *
 * @Author: jsonor
 * @Create-Time: 2017/9/28 9:21
 * @Description: 获取请求消息的参数
 */
@WebServlet(name = "requestServlet", urlPatterns = { "/request"})
public class RequestServlet extends HttpServlet {

  @Override
  protected void doGet(HttpServletRequest req,
      HttpServletResponse resp)
      throws ServletException, IOException {
    PrintWriter pw = resp.getWriter();
    printRequestLine(req, pw);
    printRequestHeader(req, pw);
  }

  /***
   * 打印出请求头中的数据
   * @param req Http请求
   * @param pw 打印流
   */
  private void printRequestHeader(HttpServletRequest req, PrintWriter pw) {
    // getHeader
    // getHeaderNames
    // getHeaders

    // 获取http 请求中所有的头的
    Enumeration<String> headerNames = req.getHeaderNames();
    while (headerNames.hasMoreElements()) {
      String name = headerNames.nextElement();
      pw.print(name);
      pw.print(" : ");
      pw.println(req.getHeader(name));
    }
  }

  /***
   * 获取请求行的方法
   * @param req Http请求
   * @param pw 打印流
   */
  private void printRequestLine(HttpServletRequest req, PrintWriter pw) {
    // 请求方法
    pw.println("method : " + req.getMethod());

    // 要访问的资源的地址
    pw.println("url : " + req.getRequestURI());

    // get参数的内容
    pw.println("param : " + req.getQueryString());

    // 协议版本
    pw.print("protocol : " + req.getProtocol());
  }
}
